package com.wlbx.agent.ui.fragment.tab;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.StrictMode;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.orhanobut.logger.Logger;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.wlbx.agent.R;
import com.wlbx.agent.base.BaseFragment;
import com.wlbx.agent.bean.AgentBean;
import com.wlbx.agent.event.HiddenTabEvent;
import com.wlbx.agent.global.AccountManager;
import com.wlbx.agent.global.Constant;
import com.wlbx.agent.ui.activity.MainActivity;
import com.wlbx.agent.util.ActivityUtil;
import com.wlbx.agent.util.BitMapUtil;
import com.wlbx.agent.util.Constants;
import com.wlbx.agent.util.SPUtil;
import com.wlbx.agent.view.bridge.BridgeHandler;
import com.wlbx.agent.view.bridge.BridgeWebView;
import com.wlbx.agent.view.bridge.BridgeWebViewClient;
import com.wlbx.agent.view.bridge.CallBackFunction;
import com.wlbx.agent.view.bridge.DefaultHandler;

import net.lucode.hackware.magicindicator.buildins.UIUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.ByteArrayOutputStream;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;

public class ReplayFragment extends BaseFragment {
    private static final String TAG = "ReplayFragment";

    @BindView(R.id.webView)
    BridgeWebView wvContent;

    @BindView(R.id.fl_video)
    FrameLayout mLayout;


    @BindView(R.id.rl_layout)
    RelativeLayout rlLayout;



    private String purl,url;
    private WebSettings webSettings;
    private IWXAPI wxApi;
    private static final int THUMB_SIZE = 150;
    private View mCustomView;	//用于全屏渲染视频的View
    private WebChromeClient.CustomViewCallback mCustomViewCallback;



    @Override
    protected int getInflateViewId() {
        return R.layout.fragment_replay;
    }

    @SuppressLint("JavascriptInterface")
    @Override
    public void initData() {
        Logger.i(JSON.toJSONString("----"+AccountManager.hasUserLogin()));
        addWXPlatform();
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads().detectDiskWrites().detectNetwork()
                .penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
                .penaltyLog().penaltyDeath().build());
        purl = Constants.onLiveUrl;
        url = purl;
        webSettings = wvContent.getSettings();
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webSettings.setDomStorageEnabled(true);
        StringBuilder userAgentBuilder= new StringBuilder(webSettings.getUserAgentString());
        webSettings.setUserAgentString(userAgentBuilder.append(";").append("native_Andriod").append(";").append("ICBC-AXA-EJBB").toString());
        wvContent.addJavascriptInterface(new ReplayFragment.JsObject(),"android");
        webSettings.setBlockNetworkImage(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            webSettings.setMediaPlaybackRequiresUserGesture(false);
        }
        wvContent.setWebViewClient(new ReplayFragment.MyWebViewClient());
        wvContent.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onShowCustomView(View view, CustomViewCallback callback) {
                super.onShowCustomView(view, callback);
                //如果view 已经存在，则隐藏
                if (mCustomView != null) {
                    callback.onCustomViewHidden();
                    return;
                }

                mCustomView = view;
                mCustomView.setVisibility(View.VISIBLE);
                mCustomViewCallback = callback;
                mLayout.addView(mCustomView);
                mLayout.setVisibility(View.VISIBLE);
                mLayout.bringToFront();

                //设置横屏
                getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                rlLayout.setPadding(0,0,0,0);
            }

            @Override
            public void onHideCustomView() {
                super.onHideCustomView();
                if (mCustomView == null) {
                    return;
                }
                mCustomView.setVisibility(View.GONE);
                mLayout.removeView(mCustomView);
                mCustomView = null;
                mLayout.setVisibility(View.GONE);
                try {
                    mCustomViewCallback.onCustomViewHidden();
                } catch (Exception e) {
                }
                rlLayout.setPadding(0, UIUtil.dip2px(getActivity(),30),0,0);

//                titleView.setVisibility(View.VISIBLE);
                getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
            }


        });
        wvContent.setDefaultHandler(new DefaultHandler());
        wvContent.loadUrl(url);
        registerHandler(wvContent);
    }
    /**
     * 横竖屏切换监听
     */
    @Override
    public void onConfigurationChanged(Configuration config) {
        HiddenTabEvent hiddenTabEvent=new HiddenTabEvent();
        super.onConfigurationChanged(config);
        switch (config.orientation) {
            case Configuration.ORIENTATION_LANDSCAPE:
                getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
//                mToolbar.setVisibility(View.GONE);

                hiddenTabEvent.setHidden(true);
                EventBus.getDefault().postSticky(hiddenTabEvent);
                break;
            case Configuration.ORIENTATION_PORTRAIT:
                getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
//                mToolbar.setVisibility(View.VISIBLE);
                hiddenTabEvent.setHidden(false);
                EventBus.getDefault().postSticky(hiddenTabEvent);
                break;
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        //清空所有cookie
        CookieSyncManager.createInstance(getActivity());
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();
        CookieSyncManager.getInstance().sync();
        if (wvContent!=null){
        wvContent.setWebChromeClient(null);
        wvContent.setWebViewClient(null);
        wvContent.getSettings().setJavaScriptEnabled(false);
        wvContent.clearCache(true);
        wvContent.destroy();
        }
    }



    @Override
    public void initEvent() {

    }


    public class JsObject{

    }
    //与H5交互操作
    public String getAgentData(String data) {
        AgentBean ab = (AgentBean)SPUtil.getBean(Constant.USER_INFO,"agent");
        Logger.i("ab---"+JSON.toJSONString(ab));
        JSONObject json = new JSONObject();
        if(ab!=null){
            json.put("accessToken",ab.getAccessToken());
            json.put("publicKey",ab.getPublicKey());
            json.put("image",ab.getImage());
            json.put("loginPwdFlag",ab.getLoginPwdFlag());
            json.put("name",ab.getName());
            json.put("workNo",ab.getWorkNo());
            json.put("iphone",ab.getMobile());
        }else{
            json.put("accessToken","");
            json.put("publicKey","");
        }
        return json.toJSONString();
    }

    public String showTitle(String data) {

        return "";
    }

    public String weixinShare(String data) {
        if (!wxApi.isWXAppInstalled()) {
            Toast.makeText(mActivity,"您还没有安装微信",Toast.LENGTH_SHORT).show();
            return "";
        }
        JSONObject json =  JSON.parseObject(data);
        //0-分享微信 1-分享朋友圈
        String shareType = json.getString("shareType");
        // SendMessageToWX.Req.WXSceneSession是分享到好友会话
        // SendMessageToWX.Req.WXSceneTimeline是分享到朋友圈
        String titleName = json.getString("titleName");
        String content = json.getString("describe");
        String shareUrl =json.getString("shareUrl");
        String imageUrl = json.getString("imageUrl");
        if("0".equals(shareType)){
            // 初始化一个WXWebpageObject对象
            WXWebpageObject webpageObject = new WXWebpageObject();
            // 填写网页的url
            webpageObject.webpageUrl = shareUrl;
            // 用WXWebpageObject对象初始化一个WXMediaMessage对象
            WXMediaMessage msg = new WXMediaMessage(webpageObject);
            // 填写网页标题、描述、位图
            msg.title = titleName;
            msg.description = content;
            if (!TextUtils.isEmpty(imageUrl)){
                // 如果没有位图，可以传null，会显示默认的图片
                msg.setThumbImage(BitMapUtil.getInstance().returnBitMap(imageUrl));
            }
            // 构造一个Req
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            // transaction用于唯一标识一个请求（可自定义）
            req.transaction = "webpage";
            // 上文的WXMediaMessage对象
            req.message = msg;
            req.scene = SendMessageToWX.Req.WXSceneSession;
            // 向微信发送请求
            wxApi.sendReq(req);
        }else if("1".equals(shareType)){
            // 初始化一个WXWebpageObject对象
            WXWebpageObject webpageObject = new WXWebpageObject();
            // 填写网页的url
            webpageObject.webpageUrl = shareUrl;
            // 用WXWebpageObject对象初始化一个WXMediaMessage对象
            WXMediaMessage msg = new WXMediaMessage(webpageObject);
            // 填写网页标题、描述、位图
            msg.title = titleName;
            msg.description = content;
            if (!TextUtils.isEmpty(imageUrl)){
                // 如果没有位图，可以传null，会显示默认的图片
                msg.setThumbImage(BitMapUtil.getInstance().returnBitMap(imageUrl));
            }
            // 构造一个Req
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = "webpage";
            req.message = msg;
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
            wxApi.sendReq(req);
        }
        return "";
    }

    public String weixinShareImage(String data) {
        if (!wxApi.isWXAppInstalled()) {
            Toast.makeText(mActivity,"您还没有安装微信",Toast.LENGTH_SHORT).show();
            return "";
        }
        JSONObject json =  JSON.parseObject(data);
        //0-分享微信 1-分享朋友圈
        String shareType = json.getString("shareType");
        String imageUrl = json.getString("imageUrl");
        Bitmap bitmap = BitMapUtil.getInstance().returnBitMap(imageUrl);
        WXImageObject imgObj = new WXImageObject(bitmap);
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;
        Bitmap thumbBitmap = Bitmap.createScaledBitmap(bitmap, THUMB_SIZE, THUMB_SIZE, true);
        bitmap.recycle();
        msg.thumbData = bmpToByteArray(thumbBitmap);  //设置缩略图
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("imgshareappdata");
        req.message = msg;
        req.scene = Integer.valueOf(shareType);
        wxApi.sendReq(req);
        return "";
    }

    public byte[] bmpToByteArray(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }
    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }


    public String appointViewController(String data) {
        JSONObject json =  JSON.parseObject(data);
        String pageIndex = json.getString("pageIndex");
        Intent intent = new Intent(mActivity, MainActivity.class);
        intent.putExtra("to",pageIndex);
        startActivity(intent);
        return "";
    }

    public String backLastPage(String data){
        return "";
    }

    /**
     * @功能描述 : 添加微信平台分享
     * @return
     */
    private void addWXPlatform() {
        wxApi = WXAPIFactory.createWXAPI(mActivity, Constants.WX_APPID);
        wxApi.registerApp(Constants.WX_APPID);
    }

    class MyWebViewClient extends BridgeWebViewClient {

        public MyWebViewClient() {
            super(wvContent);
        }

        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            super.onReceivedHttpError(view, request, errorResponse);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);

        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return super.shouldOverrideUrlLoading(view,url);
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            view.getSettings().setBlockNetworkImage(false);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            //super.onReceivedSslError(view, handler, error);
            handler.proceed();
            if(error.getPrimaryError() == SslError.SSL_INVALID ){// 校验过程遇到了bug
                handler.proceed();
            }else{
                handler.cancel();
            }
        }
    }

    public void registerHandler(BridgeWebView wvContent){
        wvContent.registerHandler("getAgentData", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Logger.i("getAgentData---"+ data);
                String ret = getAgentData(data);
                Logger.i("getAgentData---"+ ret);
                function.onCallBack(ret);
            }
        });

        wvContent.registerHandler("showTitle", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Logger.i(TAG, data);
                String ret = showTitle(data);
                function.onCallBack(ret);
            }
        });

        wvContent.registerHandler("weixinShare", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Logger.i(TAG, data);
                String ret = weixinShare(data);
                function.onCallBack(ret);
            }
        });

        wvContent.registerHandler("weixinShareImage", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Logger.i(TAG, data);
                String ret = weixinShareImage(data);
                function.onCallBack(ret);
            }
        });

        wvContent.registerHandler("appointViewController", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Logger.i(TAG, data);
                String ret = appointViewController(data);
                function.onCallBack(ret);
            }
        });

        wvContent.registerHandler("backLastPage", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Logger.i(TAG, data);
                String ret = backLastPage(data);
                function.onCallBack(ret);
            }
        });

        wvContent.registerHandler("browserEnvironment", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Logger.i("browserEnvironment---"+ data);
                String ret = "Android";
                function.onCallBack(ret);
            }
        });
    }

    public void backPre(){
        if(wvContent.canGoBack() ){
            wvContent.goBack();
        }else {
            exitBy2Click();
        }
    }

    /**
     * 双击退出函数
     */
    private static Boolean isExit = false;

    private void exitBy2Click() {
        Timer tExit = null;
        if (isExit == false) {
            isExit = true; // 准备退出
            Toast.makeText(getActivity(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务

        } else {
            ActivityUtil.getInstance().finishAllActivity();
            System.exit(0);
        }

    }

}
